package com.minelx.util.date;

import java.util.ArrayList;
import java.util.List;

public class Descriptions {

	private final List<Description> descriptions;

	public Descriptions(List<Description> descriptions) {
		this.descriptions = descriptions;
	}

	public List<CertainRange> split() {
		List<CertainRange> result = new ArrayList<>();

		Cursor<Description> descriptionCursor = new Cursor<>(descriptions);
		while (descriptionCursor.hasNext()
				&& (descriptionCursor.getIndex() != descriptions.size() - 1)) {
			Description current = descriptionCursor.pop();

			if (current.isFirstDayOfAMonth()
					&& descriptionCursor.lookup().isFirstDayOfAMonth()) {
				List<Description> them = descriptionCursor.popThem(Description::isFirstDayOfAMonth);
				descriptionCursor.revert(); // revert the last matched month
				add(result, current, them.get(them.size() - 1));
			} else {
				add(result, current, descriptionCursor.lookup());
			}
		}
		return result;
	}

	private void add(List<CertainRange> result, Description description, Description nextDescription) {
		result.add(new CertainRange(typeOfCertainRange(description, nextDescription),
				description.getAtDescription(),
				nextDescription.getAtDescription()));
	}

	private String typeOfCertainRange(Description description, Description nextDescription) {
		if (description.isFirstDayOfAMonth() && nextDescription.isFirstDayOfAMonth()) {
			return "MONTH";
		}
		return "DAY";
	}
}
